<?php
/**
 *
 *
 */
namespace Yz\modules\Error;

class Controller_Error
    extends \Yz_Controller_Templated
    implements \Yz_Controller_Interface
{

    protected $viewClass = 'Yz\modules\Error\View_Error';

    public function go( \Yz_Router_Interface $router )
    {
        $this->router = $router;
        $ex = $router->getException();
        switch (true) {
            case $ex instanceof \Yz_Access_Exception_Forbidden:
            case $ex instanceof \Yz_Access_Exception_Unauthenticated:
                return $this->gotoLogin();
            case $ex instanceof \Yz_Exception_LibraryNotFound:
            case $ex instanceof \Yz_Exception_ModuleNotFound:
                return $this->gotoNotFound();
            default:
                return $this->gotoError($ex);
        }
    }


    /**
     *  redirect externally to the login screen, printing out a short message from template
     *  @return chainable
     */
    protected function gotoLogin()
    {
        debug();
        $url = $this->router->getWebPrefix() . "users/login/?path=" . $this->getRequest()->getPath();

        $tpl = $this->selectTemplate("Login");
        $tpl->url = $url;
        $this
            ->getView()
            ->setRedirect($url)
            ;
        return $this
            ->outputTemplate($tpl)
            ;
    }

    /**
     *  redirect externally to the login screen, printing out a short message from template
     *  @return chainable
     */
    protected function gotoNotFound()
    {
        debug();
        $url = $this->getRequest()->getPath();

        $tpl = $this->selectTemplate("NotFound");
        $tpl->url = $url;
        $this
            ->getView()
            ->declareNotFound()
            ;
        return $this
            ->outputTemplate($tpl)
            ;
    }

    /**
     *  show an error page with description
     *
     */
    protected function gotoError( $ex )
    {
        debug();
        $content = "$ex\n\nStack trace:\n" . $ex->getTraceAsString();
        $tpl = $this->selectTemplate("Error");
        $tpl->message = $content;
        $this
            ->getView()
            ->declareServerError()
            ;
        return $this
            ->outputTemplate($tpl)
            ;
    }

}
